<template>
  <div ref="container" class="progressive-image">
    <!-- 小图作为背景 -->
    <img
      v-if="showPlaceholder"
      :src="placeholder"
      class="progressive-image__placeholder"
      :style="placeholderStyle"
      alt="placeholder"
    />
    <!-- 大图容器 -->
    <img
      v-show="loaded"
      :src="src"
      class="progressive-image__full"
      :class="{ 'progressive-image__full--reveal': reveal }"
      alt="full image"
      @load="handleImageLoad"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'

const props = defineProps({
  src: { type: String, required: true }, // 高清图URL
  placeholder: { type: String, required: true }, // 缩略图URL
  duration: { type: Number, default: 1.5 }, // 动画时长（秒）
  threshold: { type: Number, default: 0.1 }, // 进入视口阈值
  blur: { type: Number, default: 8 }, // 缩略图模糊度
})

const emit = defineEmits(['loaded', 'error'])

const container = ref(null)
const loaded = ref(false)
const reveal = ref(false)
const observer = ref<any>(null)
const showPlaceholder = ref(true)

// 缩略图样式
const placeholderStyle = computed(() => ({
  filter: `blur(${props.blur}px)`,
}))

// 图片加载处理
const handleImageLoad = () => {
  setTimeout(() => {
    reveal.value = true
    emit('loaded')
  }, 50)
}

// 初始化 Intersection Observer
const initObserver = () => {
  observer.value = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          // 开始加载高清图
          loaded.value = true
          observer.value.unobserve(container.value)
        }
      })
    },
    {
      rootMargin: '0px',
      threshold: props.threshold,
    },
  )

  if (container.value) {
    observer.value.observe(container.value)
  }
}

onMounted(initObserver)

onBeforeUnmount(() => {
  if (observer.value) {
    observer.value.disconnect()
  }
})
</script>

<style lang="scss" scoped>
.progressive-image {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.progressive-image__placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: 0% 0%;
  transition: filter 0.3s ease;
}

.progressive-image__full {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: 0% 0%;
  opacity: 0;
  transition: opacity v-bind('`${props.duration}s`') ease-out;
}

.progressive-image__full--reveal {
  opacity: 1;
}
</style>
